<?php
if(!defined('BASEPATH'))
		exit('No direct script access allowed');

class Authentication {
	var $_id = 0;
	var $_username = "";
	var $_password = "";
	var $_level = "";
	var $_auth = FALSE;
	function Authentication($auto = TRUE)
	{
		if($auto)
		{
			$CI =& get_instance();
			if($this->login($CI->session->userdata('username'), $CI->session->userdata('password')))
			{
				$this->_id = $CI->session->userdata('id');
				$this->_username = $CI->session->userdata('username');
				$this->_password = $CI->session->userdata('password');
				$this->_level = $CI->session->userdata('level');
			}
		}
	}
	function getId(){return $this->_id;}
	function getUsername(){return $this->_username;}
	function getPassword(){return $this->_password;}
	function getLevel(){return $this->_level;}
	
	function login($username = "", $password = "")
	{
		if(empty($username)||empty($password))
			return FALSE;

		$CI =& get_instance();		

		//$sql = "SELECT * FROM `usuario` WHERE `login`=? AND `password`=?";
		$sql="SELECT * FROM Usuario
WHERE login=? AND password=?;";
		$query = $CI->db->query($sql, array($username, $password));

		//login ok
		if($query->num_rows()==1)
		{
			$row = $query->row();

			$CI->session->set_userdata('id_usuario', $row->id_usuario);
			print_r($CI->session->set_userdata('login', $username));
			$this->_id = $row->id_usuario;
			$CI->session->set_userdata('login', $username);
			$this->_username = $username;
			$CI->session->set_userdata('password', $password);
			$this->_password = $password;
			

			$this->_auth = TRUE;

			return TRUE;
		}
		else
		{
			$this->_auth = FALSE;
			$this->logout();

			return FALSE;
		}
	}
	function login_user($username = "", $password = "")
	{
		if(empty($username)||empty($password))
			return FALSE;

		$CI =& get_instance();		

		//$sql = "SELECT * FROM `users` WHERE `username`=? AND `password`=?";
		$sql="SELECT * FROM Usuario
WHERE login=? AND password=?;";
		$query = $CI->db->query($sql, array($username, $password));

		//login ok
		if($query->num_rows()==1)
		{
			$row = $query->row();

			$CI->session->set_userdata('id', $row->id_usuario);
			$this->_id = $row->id_usuario;
			$CI->session->set_userdata('login', $username);
			$this->_username = $username;
			$CI->session->set_userdata('password', $password);
			$this->_password = $password;
			
			$this->_auth = TRUE;

			return TRUE;
		}
		else
		{
			$this->_auth = FALSE;
			$this->logout();

			return FALSE;
		}
	}
	function logout()
	{
		$CI =& get_instance();
		$CI->session->sess_destroy();
		$this->_auth = FALSE;
	}
	function check($level = 0, $strict = TRUE)
	{
		if(!$this->_auth)
			return FALSE;

		if($strict)
		{
			if($level == $this->_level)
				return TRUE;
			else
				return FALSE;
		}
		else
		{
			if($level <= $this->_level)
				return TRUE;
			else
				return FALSE;
		}
	}
}
?>